<template>
  <div class="p-2">
    <el-form ref="queryFormRef" :inline="true" label-width="90px" class="queryForm">
      <el-form-item label="出库部门" prop="selectPorductDepart">
        <el-select v-model="selectPorductDepart" placeholder="请选择" clearable style="width: 220px" filterable>
          <el-option v-for="dict in selectPorductDepartList" :key="dict.coreId" :label="dict.coreName" :value="dict.coreId" />
        </el-select>
      </el-form-item>
      <div>
        <el-button class="reset" @click="resetQuery" :loading="queryLoading">清空</el-button>
        <el-button calss="confirm" type="primary" :disabled="selectionRecordList.length === 0" @click="handleQuery" :loading="queryLoading">确认出库</el-button>
      </div>
    </el-form>
    <div class="out_bound_content">
      <div class="out_bound_content_table" id="out_bound_content_table">
        <el-table :data="selectionRecordList" border>
          <el-table-column label="序号" type="index" width="55" align="center" show-overflow-tooltip />
          <el-table-column label="商品名称" align="center" prop="styleName" show-overflow-tooltip />
          <el-table-column label="图片" align="center" prop="productImage" width="100" show-overflow-tooltip>
            <template #default="scope">
              <image-preview :src="scope.row.productImage" :width="50" :height="50" />
            </template>
          </el-table-column>
          <el-table-column label="库存编码" align="center" prop="stockCode" show-overflow-tooltip />
          <el-table-column label="商品码" align="center" prop="id" show-overflow-tooltip />
          <el-table-column label="69码" align="center" prop="styleCode" show-overflow-tooltip />
          <el-table-column label="价格" align="center" prop="price" show-overflow-tooltip>
            <template #default="scope">
              {{ scope.row.mechanismList[0].price || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="佣金" align="center" prop="commission" show-overflow-tooltip>
            <template #default="scope">
              {{ scope.row.mechanismList[0].commission ? (scope.row.mechanismList[0].commission + '%') :
                                '-' }}
            </template>
          </el-table-column>
          <el-table-column label="成本价" align="center" prop="costPrice" show-overflow-tooltip>
            <template #default="scope">
              {{ scope.row.mechanismList[0].costPrice || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="机制" align="center" prop="liveStreamingMechanism" show-overflow-tooltip />
          <el-table-column label="备注" align="center" prop="inAuditRemark" show-overflow-tooltip />
          <el-table-column label="出库数量" align="center" prop="quantity" width="200" show-overflow-tooltip>
            <template #default="scope">
              <div>
                <el-input-number v-model="scope.row.quantity" :min="1" :max="scope.row.stockInfo?.stockAvailable" />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right">
            <template #default="scope">
              <el-button type="danger" plain @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="out_bound_content_select" id="out_bound_content_select">
        <div class="drag_line" @mousedown="linemouseDown"></div>
        <div class="out_bound_content_selecton">
          <el-tabs v-model="activeTab" @tab-click="handleClick">
            <el-tab-pane label="搜索选品" name="selectedProSearch">
              <el-form ref="queryVagueRef" :inline="true" label-width="90px" class="queryForms" @submit.native.prevent>
                <el-form-item label="模糊搜索" prop="">
                  <el-input v-model="queryParams.content" placeholder="库存编码、商品名称、商品编码混合模糊搜索" clearable maxlength="20" @keyup.enter="vagueQuery" style="width: 320px;" />
                </el-form-item>
              </el-form>
              <div class="out_bound_content_product" v-loading="loading" :class="{ 'isScroll': loading }" element-loading-text="Loading..." @scroll="productScroll">
                <div class="product_item" v-for="(item, index) in selectionList" :key="index" @click="selectItem(item)">
                  <div class="product_item_image"><image-preview :src="item.productImage" :width="150" :height="120" /></div>
                  <div class="product_item_name product_items">{{ item.stockCode }}</div>
                  <div class="product_item_name product_items">{{ item.styleName }}</div>
                  <div class="product_item_bottom product_items">
                    <div class="product_item_price">{{ item.mechanismList[0]?.price ||
                                            item.mechanismList[0]?.costPrice }}</div>
                    <div class="product_item_inventory">库存：{{
                                            item.stockInfo?.stockAvailable }}
                    </div>
                  </div>
                </div>
                <div class="product_item_coverage" v-for="item in coverage" :key="item"></div>
                <div class="footer_loading" v-loading="loadingFooter" element-loading-text="Loading...">
                </div>
              </div>
            </el-tab-pane>
            <!-- <el-tab-pane label="出库历史" name="outboundHistory">
                            <el-form ref="queryVagueRef" :inline="true" label-width="70px" class="queryForms"
                                @submit.native.prevent>
                                <el-form-item label="出库码" prop="">
                                    <el-input v-model="queryParamss.qutboundCode" placeholder="出库码搜索" clearable
                                        maxlength="20" @keyup.enter="qutboundCodeQuery" />
                                </el-form-item>
                            </el-form>
                            <div class="out_bound_content_product" v-loading="loading" :class="{ 'isScroll': loading }"
                                element-loading-text="Loading..." @scroll="productScroll">
                                <div class="product_item" v-for="(item, index) in selectionList" :key="index"
                                    @click="selectItem(item)">
                                    <div class="product_item_image"><image-preview :src="item.productImage" /></div>
                                    <div class="product_item_code product_items">{{ '123456789' }}</div>
                                    <div class="product_item_name product_items">{{ item.styleName }}</div>
                                    <div class="product_item_bottom product_items">
                                        <div class="product_item_price">{{ item.price || item.costPrice }}</div>
                                        <div class="product_item_inventory">{{ '暂无库存' }}</div>
                                    </div>
                                </div>
                                <div class="footer_loading" v-loading="loadingFooter" element-loading-text="Loading...">
                                </div>
                            </div>
                        </el-tab-pane> -->
          </el-tabs>
        </div>
      </div>

    </div>
  </div>
</template>
<script setup name="OutBound" lang="ts">
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
import { queryProduct, addStockOut } from '@/api/group/productOutbound/index';
import { HmProductsVo } from '@/api/group/productOutbound/types';
import type { TabsPaneContext } from 'element-plus';
import { getDeptPage } from '@/api/group/productSelectionPricing';
const queryLoading = ref(false);
// 选品部门
const selectPorductDepart = ref();
/**
 * @content 模糊搜索
 * @qutboundCode 出库码
 */
interface OutBoundQueryParmas extends PageQuery {
  content?: string;
  qutboundCode?: undefined;
  shelvesStatus?: number;
}
const queryFormRef = ref<ElFormInstance>();
const queryVagueRef = ref<ElFormInstance>();
const queryParams = ref<OutBoundQueryParmas>({
  pageNum: 1,
  pageSize: 60,
  qutboundCode: undefined,
  shelvesStatus: 2
});
// 出库历史搜索条件
const queryParamss = ref<OutBoundQueryParmas>({
  pageNum: 1,
  pageSize: 60,
  content: undefined
});

// 补位元素数量
const coverage = ref(0);
const selectPorductDepartList = ref<{ coreId: string; coreName: string }[]>([]);
// 选中出库数据
const selectionRecordList = ref<HmProductsVo[]>([]);
// tab
const activeTab = ref('selectedProSearch');
// 筛选数据
const selectionList = ref<HmProductsVo[]>([]);
// loading
const loading = ref(false);
// 总数
const total = ref<number>(0);
// 下一页loading
const loadingFooter = ref(false);
// 防止触底后请求多次接口
const toBottom = ref(true);
/**
 * 按住事件
 * @param e
 */
const linemouseDown = (e: any) => {
  // 右侧盒子
  const rightBox = document.getElementById('out_bound_content_select');
  // 右侧盒子宽度
  const rightW = (rightBox as any).offsetWidth;
  // 鼠标X轴的值
  const disX = e.clientX;
  // 滑动事件
  document.onmousemove = (ev) => {
    (rightBox as any).style.width = rightW + (disX - ev.clientX) + 'px';
  };
  // 释放按住操作
  document.onmouseup = () => {
    document.onmousemove = null;
  };
};
/** 清空 */
const resetQuery = () => {
  selectionRecordList.value = [];
};
/** 确认出库 */
const handleQuery = async () => {
  if (!selectPorductDepart.value) {
    proxy?.$modal.msgError(`请选择选品部门!`);
  } else {
    const flag = selectionRecordList.value.every((item) => item.quantity);
    if (flag) {
      queryLoading.value = true;
      const businessList = selectionRecordList.value.map((item: any, index: number) => {
        return {
          productId: item.id,
          outNum: item.quantity,
          stockCode: item.stockCode,
          stockNum: item.stockInfo?.stockAvailable,
          outType: 1
        };
      });
      await addStockOut({
        coreUserId: selectPorductDepart.value,
        outType: 1,
        businessList
      });
      proxy?.$modal.msgSuccess('出库成功');
      selectionRecordList.value = [];
      queryLoading.value = false;
      getList();
    } else {
      proxy?.$modal.msgError(`请输入出库数量!`);
    }
  }
};
/** 模糊搜索 */
const vagueQuery = () => {
  getList();
};
/** 出库码搜索 */
const qutboundCodeQuery = () => {
  getHistoryList();
};
/** 选品查询 */
const getList = async () => {
  loading.value = true;
  const res = await queryProduct(queryParams.value);
  selectionList.value = res.data.rows;
  selectionList.value.forEach((item) => {
    item.quantity = 1;
  });
  total.value = res.data.total;
  loading.value = false;
  setWidth();
};
/** 出库历史查询 */
const getHistoryList = async () => {
  loading.value = true;
  const res = await queryProduct(queryParamss.value);
  selectionList.value = res.data.rows;
  total.value = res.data.total;
  loading.value = false;
};
/** 滚动到底部事件 */
const productScroll = async (event: any) => {
  const { scrollTop, clientHeight, scrollHeight } = event.target;
  // 到底
  if (toBottom.value) {
    if (scrollTop + clientHeight >= scrollHeight) {
      if (total.value > queryParams.value.pageNum * queryParams.value.pageSize) {
        toBottom.value = false;
        loadingFooter.value = true;
        queryParams.value.pageNum++;
        const res = await queryProduct(queryParams.value);
        selectionList.value.push(...res.data.rows);
        selectionList.value.forEach((item) => {
          item.quantity = 1;
        });
        loadingFooter.value = false;
        toBottom.value = true;
        setWidth();
      }
    }
  }
};

/**
 * 选中出库数据
 * @param row 出库数据
 */
const selectItem = (row: HmProductsVo) => {
  let index = selectionRecordList.value.findIndex((item) => item.id === row.id);
  if (index > -1) {
    ElMessage({ message: '请勿新增重复数据', type: 'error' });
  } else {
    if (row.stockInfo?.stockAvailable == 0) {
      ElMessage({ message: '该商品库存不足', type: 'error' });
    } else {
      selectionRecordList.value.push(row);
    }
  }
};
/**
 * 删除出库数据
 * @param row 数据
 */
const handleDelete = (row: HmProductsVo) => {
  selectionRecordList.value = selectionRecordList.value.filter((item) => item.id !== row.id);
};

/**
 * tabs切换
 */
const handleClick = (tab: TabsPaneContext, event: Event) => {
  selectionList.value = [];
  queryParams.value.pageNum = 1;
  queryParamss.value.pageNum = 1;
};

/** 获取选品部门 */
const anchorList = async () => {
  const res = await getDeptPage({ isOutStock: 0 });
  selectPorductDepartList.value = res.rows;
};

onMounted(() => {
  anchorList();
  getList();
});
const setWidth = () => {
  const observer: any = new ResizeObserver((entries) => {
    for (let entry of entries) {
      // 获取div元素的新宽度
      const newWidth = entry.contentRect.width;
      // 执行相应的操作，比如更新UI或调用其他函数
      coverage.value = Math.floor((newWidth - 20) / 170) - (selectionList.value.length % Math.floor((newWidth - 20) / 170));
    }
  });

  // 监听目标div元素的宽度变化
  const targetDiv = document.querySelector('#out_bound_content_select');
  observer.observe(targetDiv);
};
</script>
<style lang="scss" scoped>
.queryForm {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 50px;
}

:deep(.el-form-item__label::before) {
  content: '*';
  color: var(--el-color-danger);
  margin-right: 4px;
}

:deep(.el-form-item--default) {
  margin-bottom: 0 !important;
}

:deep(.el-tabs__nav-wrap::after) {
  height: 0px !important;
}

.reset {
  border: 1px solid #109aff;
  color: #109aff;
}

.out_bound_content {
  width: 100%;
  height: calc(100vh - 160px);
  display: flex;
  justify-content: space-between;
  align-items: center;

  .out_bound_content_table {
    height: 100%;
    min-width: 50%;
    flex: 1;
    border: 1px solid #f3f3f7;
    overflow-y: auto;
  }

  .out_bound_content_select {
    height: 100%;
    max-width: 50%;
    min-width: 28%;
    width: 28%;
    margin-left: 20px;
    position: relative;
    border: 1px solid #f3f3f7;
    border-left: none;

    .drag_line {
      width: 2px;
      height: 100%;
      position: absolute;
      left: 0;
      cursor: e-resize;
      background-color: #f3f3f7;
      z-index: 10;
    }

    .out_bound_content_selecton {
      width: 100%;
      height: 100%;
      box-sizing: border-box;
      padding: 10px;

      :deep(.el-tabs) {
        height: 100%;
      }

      :deep(.el-tabs__content) {
        height: calc(100% - 55px);
      }

      :deep(.el-tab-pane) {
        height: 100%;
      }

      .queryForms {
        width: 100%;
        height: 50px;
      }

      .isScroll {
        overflow: hidden !important;
        width: 100%;
        height: calc(100% - 50px);
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
        align-items: center;
      }

      .out_bound_content_product {
        width: 100%;
        height: calc(100% - 50px);
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
        align-items: center;
        // padding: 10px;
        overflow-y: auto;
        align-content: flex-start;

        .product_item_coverage {
          width: 150px;
          margin: 10px;
        }

        .product_item {
          width: 150px;
          height: 240px;
          display: flex;
          flex-wrap: wrap;
          align-content: space-between;
          padding-bottom: 10px;
          margin: 10px;
          cursor: pointer;
          background: #f3f3f7;

          .product_items {
            width: 100%;
            padding: 0 10px;
          }

          .product_item_name {
            text-overflow: ellipsis;
            overflow: hidden;
            word-break: break-all;
            white-space: nowrap;
            font-weight: 500;
            font-size: 16px;
            color: #1a1b1c;
          }

          .product_item_bottom {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .product_item_price {
              font-size: 18px;
              color: #109aff;
            }

            .product_item_inventory {
              font-size: 14px;
              color: #afb6c3;
            }
          }

          .product_item_image {
            width: 100%;
            height: 50%;

            .el-image {
              width: 100%;
              height: 100%;
            }
          }
        }

        .footer_loading {
          width: 100%;
          height: 70px;
        }
      }
    }
  }
}
</style>